//
//  Request.m
//  JSToNativeDemo
//
//  Created by mouxiaochun on 15/7/6.
//  Copyright (c) 2015年 mouxiaochun. All rights reserved.
//

#import "AIRequest.h"
#import "AIAFNetwork.h"
#import <CommonCrypto/CommonDigest.h>
#import "AIResultParser.h"
#import "HivesHealthyConfig.h"
#import "Methods.h"
#import "AIFileManager.h"
#import "AIResultParser.h"




@implementation NSString(md5)

- (NSString *) stringFromMD5
{
  
  if(self == nil || [self length] == 0)
    return nil;
  
  const char *value = [self UTF8String];
  
  unsigned char outputBuffer[CC_MD5_DIGEST_LENGTH];
  CC_MD5(value, strlen(value), outputBuffer);
  NSMutableString *outputString = [[NSMutableString alloc] initWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
  for(NSInteger count = 0; count < CC_MD5_DIGEST_LENGTH; count++){
    [outputString appendFormat:@"%02x",outputBuffer[count]];
  }
  return outputString ;
}

@end

@interface AIRequest ()
{
  
  AICompletionBlock   _block;
  
  BOOL                _isUpdatedFromServer;
  
  NSString*           _cacheKey;
  
  AIResult*           _result;
  
  NSString*           _method;
  
  NSString*           _fill;
}

@end

@implementation AIRequest


#pragma mark --- 设置服务器访问地址
 
static NSString *_serverURL = HH_SERVER_URL;
 


+ (void)configServerURL: (NSString *)url {
  _serverURL = nil;
  _serverURL = url ;
}



/**
 *  数据请求，接口参数不需要做加密处理，可以直接调用此方法
 *
 *  @param type      请求类型
 *  @param url       请求路径,可为字符串，也可为NSURL
 *  @param jsonParam json参数
 *  @param block     回调
 *
 *  @return 请求实体
 */
+(instancetype)startWithRequestToURL:(id)url
                           jsonParam:(id)jsonParam
                               block:(AICompletionBlock)block{
  
  
  return [self startWithRequestToURL:url
                           jsonParam:jsonParam
                             encrypt:NO
                               block:block];
}

/**
 *  数据请求，使用该方法，需要传入‘encrypt’，可控制参数是否需要加密处理
 *
 *  @param type      请求类型
 *  @param url       请求路径,可为字符串，也可为NSURL
 *  @param jsonParam json参数
 *  @param block     回调
 *
 *  @return 请求实体
 */
+(instancetype)startWithRequestToURL:(id)url
                           jsonParam:(id)jsonParam
                             encrypt:(BOOL)encrypt
                               block:(AICompletionBlock)block

{
  
  return [[[self class] alloc] initWithRequestToURL:url
                                             method:nil
                                          jsonParam:jsonParam
                                            encrypt:(BOOL)encrypt
                                              block:block];
}



+ (instancetype)startWithRequestToURL:(id)url
                               method:(NSString *)method
                            jsonParam:(id)jsonParam
                              encrypt:(BOOL)encrypt
                                block:(AICompletionBlock)block {
  
  return [[[self class] alloc] initWithRequestToURL:url
                                             method:method
                                          jsonParam:jsonParam
                                            encrypt:encrypt
                                              block:block];
  
  
}


- (instancetype)initWithRequestToURL:(id)url
                              method:(NSString *)method
                           jsonParam:(id)jsonParam
                             encrypt:(BOOL)encrypt
                               block:(AICompletionBlock)block
{
  
  self = [super init];
  if (self) {
    
    _result = AIResult.new;
    _requestParams = [NSMutableDictionary dictionary];
    _method = method;
    //添加不需要加密的公共参数
    if (jsonParam) {
      [_requestParams addEntriesFromDictionary:jsonParam];
    }
    
    _isParser = YES;
    //记录是否需要加密
    _encrypt = encrypt;
    //保存block
    _block = block;
    
    _requestURL = url;
    
      if ([_method isEqualToString:_uploadHeadPic]) {
          [self uploadFile];
      }else
          [self request];

  }
  return self;
  
}





#pragma mark --- 执行blocks
-(void)excuteBlock{
  if (_block) {
    _result.isUpdatedFromServer = self.isCache;
    _block(_result);
    if (!_isRetainBlock) _block = nil;
  }
}


-(void)excuteBlockWithObject:(id)object{
  //未超时
  if (_block) {
    _result.isUpdatedFromServer = self.isCache;
    _result.object = object;
    _block(_result);
    if (!_isRetainBlock) _block = nil;
  }
}



-(NSString *)requestURL{
  if (!_requestURL) {
    _requestURL = [_serverURL stringByAppendingString:@""];
//      _requestURL = [_serverURL stringByAppendingString:_method];
  }

  return _requestURL;
}


/**
 *  需要获取缓存数据
 */
-(void)cache {
 
    _isCache = YES;
    NSString *param = [self.requestParams description];
    NSString   *url = [[self requestURL] stringByAppendingPathComponent:param];
    NSString *key = [url stringFromMD5];
    id object = [AIFileManager objectForKey:key];
    if (object) {
        _isRetainBlock = YES;//缓存后，应该继续保存block
        
        [self handleResponse:object responseData:nil];
    }

}

/**
 *  需要保存缓存数据
 */
-(void)cacheData:(NSData *)responseData {
    NSString *param = [self.requestParams description];
    NSString   *url = [[self requestURL] stringByAppendingPathComponent:param];
    NSString *key = [url stringFromMD5];
    [AIFileManager   setObject:responseData forKey:key];
}


+ (void) setRequestHeaders:(NSDictionary *)headerParams{

    requestHeaders = headerParams;
}

+ (NSDictionary *) requestHeaders{

    return requestHeaders;
}


@end




